<template>
  <view class="mobile-item-container">
    <Navbar title="添加客户" bgColor="#fff" :h5Show="false" :autoBack="true" :border="true" :onpageshow="false"></Navbar>
    <u--form labelPosition="left" :model="model" :rules="rules" ref="uForm" labelWidth="100">
      <u-form-item label="姓名" prop="name" borderBottom ref="name" required>
        <u--input v-model="model.name" border="none" placeholder="请输入内容"></u--input>
      </u-form-item>
      <u-form-item label="手机号" prop="mobile" borderBottom ref="mobile" required>
        <u--input v-model="model.mobile" border="none" placeholder="请输入内容"></u--input>
      </u-form-item>
      <u-form-item label="城市" borderBottom required @click="openPoup()">
        <u-input readonly v-model="model.address" border="none" placeholder="请选择" style="pointer-events:none" />
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-picker ref="uPicker" :show="areaPickerShow" :columns="addressColumns" :defaultIndex="areaDetault"
        :closeOnClickOverlay="true" @confirm="nationSel($event, 'area')" @cancel="areaPickerShow = false"
        @close="areaPickerShow = false" @change="changeHandler">
      </u-picker>
      <u-form-item label="备注" prop="remark" borderBottom ref="remark">
        <u--textarea v-model="model.remark" placeholder="请输入内容" border="none" confirm-type="send"></u--textarea>
      </u-form-item>
    </u--form>
    <u-button style="margin-top: 5vh;" @click="submit" type="primary">提交</u-button>
  </view>
</template>
  
<script>
import * as NoticeApi from '@/api/work/notice'
import Navbar from '@/components/navbar/Navbar'
import areaData from '@/utils/pac.json'
import { postCustomers } from '@/api/api'

export default {
  components: {
    Navbar,
  },
  data() {
    return {
      model: {
        name: '',
        address: '',
        city: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
        ],
        address: [
          { required: true, message: '请选择城市', trigger: ['blur', 'change'] }
        ]
      },

      areaPickerShow: false,    //控制弹窗显示与隐藏
      areaData: areaData,    //原始数据
      addressColumns: [],  //数据数组
      areaDetault: [],    //数据回显时的默认数据
    }
  },
  created() {
  },
  methods: {
    goBack() {
      console.log('goBack');
      uni.navigateBack({
        delta: 1, // 返回上一级页面
      });
    },

    openPoup() {
      this.areaDetault = [0, 0];
      this.areaPickerShow = true;
      this.getAreaList();
    },

    getAreaList() {
      //省的数组
      const provinceData = this.areaData.map(e => {
        return e.name
      })
      //市的数组
      const cityData = this.areaData.map(e => {
        const arr = []
        arr.push(
          e.children.map(c => {
            return c.name
          })
        )
        return arr
      })
      const arr = [provinceData, cityData[0][0]] //组装
      this.addressColumns = arr
    },

    // 选中时执行
    changeHandler(e) {
      const { columnIndex, index, indexs, picker = this.$refs.uPicker } = e
      if (columnIndex === 0) {
        const children1 = this.areaData[index].children.map(e => {
          return e.name
        })
        picker.setColumnValues(1, children1)
      }
      if (columnIndex === 1) {
        const children3 = this.areaData[indexs[0]].children[indexs[1]].children.map(e => {
          return e.name
        })
      }
    },
    // 选择框确认按钮（有多个选择器时用type进行判断）
    nationSel(event, type) {
      let value = event.value
      this.model.city = value[1];
      this.model.address = value.join('/');
      this.areaPickerShow = false
    },
    // 根据回显数据设置默认选中项
    setDefault() {
      // 户籍所在地
      let temp = []
      temp = this.model.address.split('/')
      let index, index1 = 0
      let arr, arr1 = []
      //市区对应每列的第几个
      this.areaData.forEach((item, i) => {
        if (item.name == temp[0]) {
          index = i
          item.children.forEach((val, ind) => {
            if (val.name == temp[1]) {
              index1 = ind
            }
          })
        }
      })
      //匹配省市区对应每列的第几个
      arr = this.areaData.map(e => {
        return e.name
      })
      arr1 = this.areaData[index].children.map(e => {
        return e.name
      })
      this.addressColumns = [arr, arr1]
      this.areaDetault = [index, index1]
    },

    submit() {
      this.$refs.uForm.validate().then(valid => {
        if (valid) {
          // 调用 API 提交数据示例
          postCustomers(this.model).then(res => {
            uni.showToast({ title: '提交成功' });
            uni.navigateBack(); // 提交成功后返回上一页
          }).catch(err => {
            uni.showToast({ title: res.msg, icon: 'none' });
            console.error(err);
          });
        } else {
          // 验证未通过，uView 会自动提示错误信息
          uni.showToast({ title: '请检查表单内容', icon: 'none' });
          return false;
        }
      });
    }


  }
}
</script>
  
<style lang="scss" scoped>
.notice-item-tips {
  border-radius: 8px;
  background-color: #f4f4f5;
  padding: 9px 16px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}

// /deep/.uni-input-input:disabled {
//   width: 70vw !important;
// }
</style>